import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { Skeleton } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import style from './Style.module.less'
import NumberSelector from '../NumberSelector'
import { colors } from '@js/config'
echarts.use([PieChart, TitleComponent, CanvasRenderer, LegendComponent])
function ChartBlock ({ year: y, getData, height, getEvents, type, changeYear, searchVersion, causeaction, timeType }) {
  const [year, setYear] = useState(0)
  const [ready, setReady] = useState(false)
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const [version, setVersion] = useState(0)

  useEffect(() => {
    if (version === searchVersion && year === y) {
      return
    }
    setReady(false)
    getData(y, causeaction, timeType)
      .then(res => {
        setVersion(searchVersion)
        setYear(y)
        setReady(true)
        setList(res.list)
        setTotal(res.total)
      })
  }, [causeaction, getData, searchVersion, timeType, version, year, y])

  return (
    <div className={style['chart-block']}>
      <div className={style['year-selector']}>
        <NumberSelector value={year} onChange={v => { changeYear(v) }} />
      </div>
      <div className={style.chart}>
        {ready ? (
          <ReactEchartsCore style={{ width: '100%', height: `${height}px` }} echarts={echarts} option={getOptions(year, list, total, type)} onEvents={getEvents(year)} />
        ) : (
          <div className={style['loading-box']}>
            <Skeleton active />
          </div>
        )}
      </div>
    </div>
  )
}

ChartBlock.proptypes = {
  type: PropTypes.string,
  getData: PropTypes.func,
  getEvents: PropTypes.func,
  height: PropTypes.number,
  year: PropTypes.number,
  changeYear: PropTypes.func,
  searchVersion: PropTypes.number,
  causeaction: PropTypes.array,
  timeType: PropTypes.string
}

ChartBlock.defaultProps = {
  type: '',
  getData: () => Promise.resolve({ list: [], total: 0 }),
  getEvents: (year) => ({}),
  height: 240,
  year: 0,
  changeYear: () => {},
  searchVersion: 0,
  causeaction: [],
  timeType: ''
}

// 获取配置
function getOptions (year, list, total, type) {
  const map = {}
  list.forEach(li => {
    map[li.name] = {
      name: li.name,
      value: type === 'casenum' ? li.value : transferUnit(li.value),
      percent: total ? Math.round(li.value / total * 10000) / 100 + '%' : '0%'
    }
  })
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      top: 40,
      left: '55%',
      icon: 'circle',
      itemGap: 4,
      itemWidth: 8,
      selectedMode: false,
      formatter: (name) => {
        const o = map[name]
        if (o) {
          return `{c|${litmitStr(o.name)}}\n {b|${o.value}} {a|(${o.percent})}`
        }
      },
      textStyle: {
        rich: {
          a: {
            color: '#B7BBC8',
            lineHeight: 20
          },
          b: {
            color: '#7E889C',
            lineHeight: 20
          },
          c: {
            color: '#1F2229',
            lineHeight: 20
          }
        }
      }
    },
    series: [
      {
        name: `${year}金融立案情况`,
        type: 'pie',
        radius: ['52%', '75%'],
        center: ['30%', '50%'],
        height: 240,
        itemStyle: {
          borderWidth: 5,
          borderType: 'solid',
          borderColor: 'rgba(255, 255, 255, 1)'
        },
        label: {
          show: true,
          position: 'center',
          formatter: type === 'casenum' ? `{a|${year}年数量}\n{b|${total}件}` : `{a|${year}年标的}\n{b|${transferUnit(total)}}`,
          backgroundColor: '#fff',
          rich: {
            a: {
              color: '#7E889C',
              lineHeight: 20,
              fontSize: 16
            },
            b: {
              color: '#1F2229',
              lineHeight: 40,
              fontSize: 24
            }
          }
        },
        data: list.map((li, i) => {
          const d = {
            ...li,
            itemStyle: {
              color: colors[i]
            }
          }
          return d
        })
      }
    ]
  }
}

// 限制文本长度
function litmitStr (s) {
  if (typeof s !== 'string') {
    return s
  }
  if (s.length > 10) {
    return s.slice(0, 9) + '...'
  }
  return s
}

// 转换单位
function transferUnit (v) {
  if (v > 100000000) {
    return Math.round(v / 1000000) / 100 + '亿'
  }
  if (v > 10000) {
    return Math.round(v / 100) / 100 + '万'
  }
  return v
}

export default ChartBlock
